import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageTransferOrderService } from '../../xstorage-manage-services/storage-transfer-order.service';

@Component({
  selector: 'app-storage-transfer-handle-put',
  templateUrl: './storage-transfer-handle-put.component.html',
  styleUrls: ['./storage-transfer-handle-put.component.scss']
})
export class StorageTransferHandlePutComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {};

  detailedTableData: any[] = [];

  storeOptions: any[] = []; // 仓库Options
  locationOptions: any[] = []; // 库位Options
  allocationTypeOptions: any = []; // 调拨类型Options

  editGoodsItem: any = {};

  qualityOptions: any[] = [
    {value: -1, label: '同出库品质'},
    {value: 0, label: '不良品'},
    {value: 1, label: '良品'}
  ];

  subDataLoading = false;
  warehousOverLoading = false;

  /**
   * SN信息 Modal
   * ---------------------------------------------------------------- 
   */
  isSninfoVisible = false;
  sninfoTableData: any[] = [];

  /**
   * 多库位 Modal
   * ---------------------------------------------------------------- 
   */
  isMoreLocationVisible = false;
  setLocationData: any[] = [];

  constructor(
    private msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private fb: FormBuilder,
    private commonService: CommonService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageTransferOrderService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadAllocationTypeOptions();
    this.loadStoreList();
    // this.loadLocationOptions();

    this.loadDetailsData();
  }

  // 调拨类型Options
  async loadAllocationTypeOptions() {
    const res = await this.commonService.getDictList('allocation_type');
    this.allocationTypeOptions = res || [];
  }

  // 查询仓库
  async loadStoreList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.storeOptions = data?.records.filter((item: any) => [1].includes(item.state));
    } else {
      this.msg.error(message);
    }
  }

  // 查询库位Options
  async loadLocationOptions() {
    let params = {
      whId: !this.commonService.isEmpty(this.detailsData.warehousingWhId) ? this.detailsData.warehousingWhId : '',
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getLocationList(params);
    if (code === 0) {
      this.locationOptions = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  async loadDetailsData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getAllocationDetailData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const {delivery, list} = data || {};

      if (delivery.state !== 5) {
        this.msg.error('当前状态已不等于待入库、将自动跳转到“调拨操作”页面')
                  .onClose.subscribe(() => {
                    this.pageBack();
                  });
      }

      this.detailsData = delivery || {};
      this.detailedTableData = list || [];
      this.loadLocationOptions();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 操作SN Modal
   * ---------------------------------------------------------------- 
   */
  showSninfoModal(item: any) {
    this.editGoodsItem = item;
    this.sninfoTableData = !this.commonService.isEmpty(item.deliveryItemSns) ? JSON.parse(item.deliveryItemSns) : [];
    
    this.isSninfoVisible = true;
  }

  subSninfoData() {
    let setIndex = this.detailedTableData.findIndex(item => item.whGoodsId === this.editGoodsItem.whGoodsId);
    this.detailedTableData[setIndex].deliveryItemSns = this.sninfoTableData.length ? JSON.stringify(this.sninfoTableData) : '';
    this.detailedTableData[setIndex].actualWarehousingNumber = this.sninfoTableData.length;
    this.isSninfoVisible = false;
  }

  /**
   * 多库位 Modal
   * ---------------------------------------------------------------- 
   */
  showMoreLocationModal(item: any) {
    this.editGoodsItem = item;
    this.setLocationData = item.warehousingLibraryText ? JSON.parse(item.warehousingLibraryText) : [];
    this.isMoreLocationVisible = true;
  }

  // Input 快捷切换操作(录入SN、多库位 modal使用)
  snCodeKeDowm(e: any, index: number, idstr: string) {
    let evKey = window.event || e;
    if (evKey.keyCode === 13) {
      if (idstr === 'snInput' && index === (this.setLocationData.length - 1)) {
        // this.addSnLineData();
      }
      if (idstr === 'numInput' && index === (this.setLocationData.length - 1)) {
        this.addLocationLineItem();
      }

      setTimeout(() => {
        let iptDom = document.getElementById(idstr + (index + 1));
        iptDom?.focus();
      })
    }
  }

  addLocationLineItem() {
    this.setLocationData = [
      ...this.setLocationData,
      {
        warehousingQuality: '', // 入库品质
        warehousingLibraryId: '', // 入库库位ID
        num: '' // 入库数量
      }
    ];
  }

  deleteKwItem(index: number) {
    this.setLocationData = this.setLocationData.filter((d: any, i: number) => i !== index);
  }

  submitSetLocation() { 
    let flArrs = this.setLocationData.filter(m => !this.commonService.isEmpty(m.warehousingQuality) || !this.commonService.isEmpty(m.warehousingLibraryId) || !this.commonService.isEmpty(m.num));
    if (flArrs.length) {
      // 库位不可重复
      let repeatArrs: any[] = [];
      let repeatNum: number = 0;
      flArrs.forEach((ele: any) => {
        if (!this.commonService.isEmpty(ele.warehousingLibraryId)) {
          if (repeatArrs.includes(ele.warehousingLibraryId)) {
            repeatNum += 1;
          } else {
            repeatArrs.push(ele.warehousingLibraryId);
          }
        }
      })
      if (repeatNum > 0) {
        this.msg.warning('库位不可重复');
        return
      }

      // 两者其中之一不为空，提示
      let isEmptyPz = flArrs.some(m => this.commonService.isEmpty(m.warehousingQuality));
      let isEmptyKw = flArrs.some(m => this.commonService.isEmpty(m.warehousingLibraryId));
      let isEmptyNum = flArrs.some(m => this.commonService.isEmpty(m.num));
      if (isEmptyPz) {
        this.msg.warning('调入品质不能为空');
        return
      } else if (isEmptyKw) {
        this.msg.warning('库位不能为空');
        return
      } else if (isEmptyNum) {
        this.msg.warning('入库数量不能为空');
        return
      }
    }

    let subArrs = this.setLocationData.filter(item => !this.commonService.isEmpty(item.warehousingQuality) && !this.commonService.isEmpty(item.warehousingLibraryId) && !this.commonService.isEmpty(item.num));
    if (!subArrs.length) {
      this.msg.warning('所提交数据暂未填写');
      return
    }

    let setIndex = this.detailedTableData.findIndex(item => item.whGoodsId === this.editGoodsItem.whGoodsId);
    this.detailedTableData[setIndex].warehousingLibraryText = subArrs.length ? JSON.stringify(subArrs) : '';
    this.detailedTableData[setIndex].actualWarehousingNumber = subArrs.reduce((total, item) => { return total + (item.num || 0) }, 0);
    this.isMoreLocationVisible = false;
  }

  /**
   * 暂存
   */
  async subTemporaryData() {
    let arrs = this.detailedTableData.map(ele => {
      return {
        whGoodsId: ele.whGoodsId, // 商品ID
        state: (this.routeParams.id && !this.commonService.isEmpty(ele.lineState)) ? ele.lineState : 0, // 状态 0正常(新增默认) 1已作废
        type: ele.type,  // 商品列表type为分类 (注: 选择SN则为指定sn) // type: 0 指定SN 1SN管控 2多库位 3普通(新增默认)

        deliveryNumber: ele.deliveryNumber || '', // 预计出库数量
        actualDeliveryNumber: ele.actualDeliveryNumber || '', // 实际出库数量
        deliveryQuality: !this.commonService.isEmpty(ele.deliveryQuality) ? ele.deliveryQuality : '', // 出库品质
        deliveryItemSns: ele.deliveryItemSns || '', // 出库SN
        deliveryLibraryText: ele.deliveryLibraryText || '', // 出库库位list

        warehousingNumber: ele.warehousingNumber || '', // 预计入库数量
        actualWarehousingNumber: ele.actualWarehousingNumber || '', // 实际入库数量
        warehousingQuality: !this.commonService.isEmpty(ele.warehousingQuality) ? ele.warehousingQuality : '', // 入库品质
        warehousingItemSns: ele.warehousingItemSns || '', // 入库SN
        warehousingLibraryText: ele.warehousingLibraryText || '', // 入库库位list
      }
    });

    let params = {
      allocation: {
        id: this.routeParams.id
      },
      list: arrs,
      isDelivery: 0 // 1出库 0入库
    }
    // return
    this.subDataLoading = true;
    const {code, message}: any = await this.services.updateAllocationData(params, 1);
    this.subDataLoading = false;

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadDetailsData();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 入库完毕
   */
  subWarehousOver() {
    let putArrs = this.detailedTableData.filter(item => {
      return item.lineState === 0 && (item.actualDeliveryNumber != item.actualWarehousingNumber);
    })
    if (putArrs.length && this.detailedTableData.length) {
      let tipStr = `商品 <b>[${putArrs.map(m => m.whGoodsName).join('、')}]</b> 的入库数量和实际出库数量不符，请检查`;
      this.msg.warning(tipStr);
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认后单据将彻底调拨完成并且不可操作，该操作不可逆，确认已经入库完毕?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ids: [this.routeParams.id],
          note: '',
          state: 6
        }
        this.warehousOverLoading = true;
        const {code, data, message}: any = await this.services.allocationExamineData(params);
        this.warehousOverLoading = false;
    
        if (code === 0) {
          this.msg.success(data);
          this.pageBack();
        } else {
          this.msg.error(message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * other
   * ----------------------------------------------------------------
   */

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    const calcArrs = this.detailedTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  locationChange(val: any, index: number, arrs: any[]) {
    let tempObj = this.locationOptions.find(item => item.id === val);
    arrs[index].name = tempObj?.name || '';
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  coprText(str: any) {
    this.commonService.copyStr(str);
  }

  downFile(item: any) {
    this.commonService.downLoadUrlFile(item.url);
  }

  pageBack() {
    history.back();
  }

  // 批量品质选择(选择SNModal)
  batchQualitySelect(item: any) {
    this.sninfoTableData.forEach((ele: any) => {
      if (item.value === -1) {
        // 同出库品质
        ele.warehousingQuality = ele.deliveryQuality;
      } else {
        ele.warehousingQuality = item.value;
      }
    })
  }

  // 批量库位选择(选择SNModal)
  batchLocationSelect(item: any) {
    this.sninfoTableData.forEach((ele: any) => {
      ele.warehousingLibraryId = item.id;
    })
  }

  // 批量选择品质(多库位Modal)
  batchLocationQuality(item: any) {
    this.setLocationData.map(ele => ele.warehousingQuality = item.value);
  }
}
